import axios from 'axios'
import { Message } from 'element-ui'

// 创建请求实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000, // request timeout
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    const res = response.data
    console.log('请求后端接口数据', res)

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        // 操作失败 账号错误
        message: dealMessage(res.message) || 'Error',
        type: 'error',
        duration: 5 * 1000,
      })

      console.log('操作失败，阻断操作')
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // console.log('接口响应数据: ', JSON.stringify(res))
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

/**
 * 处理报错信息
 * @param msg 报错信息
 */
function dealMessage(msg) {
  console.log('打印日志', msg)
  if (msg == null) {
    return ''
  } else {
    return msg.split(' ')[1]
  }
}

/**
 * 获取请求key防止水平越权
 * @returns 请求key
 */
function getRequestKey() {
  const now = new Date()
  return Math.floor(now.getTime() / 1000)
}

export default service
